package mc.support.orm.handler;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created with IntelliJ IDEA. <br/>
 * Author: Francis Yun    <br/>
 * Date: 2014-03-24  <br/>
 */
public class BooleanTypeHandler implements TypeHandler {

    private static final byte YES = 1;

    private static final byte NO = 0;

    private static final byte NULL = -1;

    @Override
    public Object getResult(CallableStatement cs, int columnIndex) throws SQLException {
        byte value = cs.getByte(columnIndex);
        if (YES == value) {
            return Boolean.TRUE;
        } else if (NO == value) {
            return Boolean.FALSE;
        }
        return null;
    }

    @Override
    public Object getResult(ResultSet rs, int columnIndex) throws SQLException {
        byte value = rs.getByte(columnIndex);
        if (YES == value) {
            return Boolean.TRUE;
        } else if (NO == value) {
            return Boolean.FALSE;
        }
        return null;
    }

    @Override
    public void setParameter(PreparedStatement ps, int columnIndex,
                             Object parameter, JdbcType jdbcType) throws SQLException {
        byte value = NULL;
        if (null != parameter) {
            value = (Boolean) parameter ? YES : NO;
        }
        ps.setByte(columnIndex, value);
    }

    @Override
    public Object getResult(ResultSet rs, String columnName) throws SQLException {
        byte value = rs.getByte(columnName);
        if (YES == value) {
            return Boolean.TRUE;
        } else if (NO == value) {
            return Boolean.FALSE;
        }
        return null;
    }

}
